<template>
  <div className="basic-table">
    <basic-container>
      <!-- 查询条件 -->
      <el-form :inline="true"  class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="true_name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="sex" placeholder="请选择性别">
            <el-option label="全部" value="-1"></el-option>
            <el-option label="男" value="0"></el-option>
            <el-option label="女" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" icon="el-icon-plus" @click="add">添加</el-button>
      <!-- 查询条件 -->
      <!-- 表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        @row-contextmenu="contextmenu">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column
          :formatter="dateFormat"
          prop="create_date"
          label="日期"
          width="180"
          >
        </el-table-column>
        <el-table-column
          prop="true_name"
          label="姓名"
          width="200">
        </el-table-column>
        <el-table-column
          label="性别"
          width="200">
          <template slot-scope="scope">
              <div v-if="scope.row.sex == 0">男</div>
              <div v-if="scope.row.sex == 1">女</div>
              <div v-if="scope.row.sex == undefined">无</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="200">
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="edit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="deleteUser(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格 -->
      <!-- 分页 -->
      <!--<el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page="currentPage"
        :total="totalCount">
      </el-pagination>-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
      </el-pagination>
      <!-- 分页 -->
      <!-- 新建用户弹层 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="33%" >
        <el-form ref="user" :model="user" label-width="80px">
          <input v-model="user.user_id" type="hidden">
          <el-form-item label="真实姓名">
            <el-input v-model="user.true_name"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="user.sex">
              <el-radio label="0">男</el-radio>
              <el-radio label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="email" label="邮箱" :rules="[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]">
          <el-input v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              name="file_data"
              class="avatar-uploader"
              action="/user/uploadimg.shtml"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <input v-model="user.photo" type="hidden">
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
        </span>
      </el-dialog>
      <!-- 新建用户弹层 -->
    </basic-container>
  </div>


</template>

<script>
  import BasicContainer from '@vue-materials/basic-container'
  import moment from 'moment'
  export default {
    components: { BasicContainer },
    name: 'BasicTable',
    data() {
      return {
        pageSize: 10,//每页的数据条数
        currentPage: 1,//默认开始页面
        totalCount: 1000,
        tableData: [],
        true_name: '',
        sex: '',
        user: {
          true_name: '',
          user_id: '',
          sex: '0',
          domains: [{
            value: ''
          }],
          email: '',
          photo: ''
        },
        dialogTitle: '新建用户',
        dialogVisible: false,
        imageUrl: ''

      }
    },
    methods: {
      //时间格式化
      dateFormat:function(row, column) {
        var date = row[column.property];
        if (date == undefined) {
          return "";
        }
        return moment(date).format("YYYY-MM-DD HH:mm:ss");
      },
      // 发送ajax请求，获取用户列表
      loadData: function(true_name,sex,pageNum,pageSize) {
        var that = this;
        /*this.$axios.get('http://localhost:7654/test?id=123&name=你好')*/
        this.$axios.post('/user/test.shtml', {
            true_name: true_name,
            sex: sex,
            pageNum: pageNum,
            pageSize: pageSize
          }).then(function (response) {
            console.log(response)
            var data = response.data.rows;
            that.tableData = data;
            that.totalCount = response.data.total;
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      onSearch(){
        this.loadData(this.true_name,this.sex,this.currentPage,this.pageSize);
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.loadData(this.true_name,this.sex,this.currentPage, this.pageSize);
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.loadData(this.true_name,this.sex,this.currentPage,this.pageSize);
      },
      onSubmit(){
        var that = this;
        var qs = require('querystring');
        this.$axios.post('/user/add.shtml', qs.stringify(this.user)).then(function (response) {
          console.log(response)
          if(response.data.flag){
            that.dialogVisible=false
            that.loadData(that.true_name,that.sex,that.currentPage,that.pageSize);
            that.$message({
              message: '创建成功',
              type: 'success',
              duration: '2000'
            });
            that.user = {
              true_name: '',
              user_id: '',
              sex: '',
              domains: [{
                value: ''
              }],
              email: '',
              photo: ''
            };
          }else{
            that.$message({
              message: '创建失败',
              type: 'error',
              duration: '2000'
            });
            that.user = {
              true_name: '',
              user_id: '',
              sex: '',
              domains: [{
                value: ''
              }],
              email: ''
            };
          }
        })
        .catch(function (error) {
          console.log(error);
        });
      },
      add(){
        this.dialogVisible = true;
        this.user = {
          true_name: '',
          user_id: '',
          sex: '0',
          domains: [{
            value: ''
          }],
          email: '',
          photo: ''
        };
        this.imageUrl = '';
      },
      edit(index, row){
        /*this.user = Object.assign({}, row);
        this.user.sex = ''+row.sex+'';*/
        this.user = {
          true_name: row.true_name,
          user_id: row.user_id,
          sex: ''+row.sex+'',
          domains: [{
            value: ''
          }],
          email: row.email,
          photo: row.photo
        };
        this.imageUrl = row.host_photo;
        this.dialogTitle = "修改用户";
        this.dialogVisible = true;
      },
      deleteUser(index, row){
        this.$confirm('确定要删除该用户吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var that = this;
          this.$axios.post('/user/delete.shtml?user_id='+row.user_id).then(function (response) {
            if(response.data.flag){
              that.loadData(that.true_name,that.sex,that.currentPage,that.pageSize);
              that.$message({
                message: '删除成功',
                type: 'success',
                duration: '2000'
              });

            }else{
              that.$message({
                message: '删除失败',
                type: 'error',
                duration: '2000'
              });
            }
          })
            .catch(function (error) {
              console.log(error);
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleAvatarSuccess(res, file) {
        console.log(res);
        this.imageUrl = res.hostPhoto;
        this.user.photo = res.photo;
        //this.user.imageUrl = URL.createObjectURL(file.raw);
        console.log(this.imageUrl)
      },
      beforeAvatarUpload(file) {
        //const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        /*if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }*/
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        //return isJPG && isLt2M;
        return isLt2M;
      },
      contextmenu(){
        alert(1)
      }
    },
    mounted: function() {
      // 页面加载执行方法
      this.loadData(this.true_name,this.sex,this.currentPage,this.pageSize);
    }
  }

</script>

<style>
  .basic-table {

  }
  .demo-form-inline{
    float: left;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
